<?php

?>

<div class="hidden" id="addCntForm-cont">
    <form class="well form-inline margin-horisontal login" action="" method="POST" name="addCntForm" id="addCntForm">
        <fieldset>

            <input type="hidden" name="action" value="<?php echo ACTIONS::CONTACT_NEW; ?>">
            <input type="hidden" name="cnt_id" value="<?php echo Arr::getValue($params, 'id', 0); ?>">

            <div class="control-group" id="cg-lastname">
                <label class="control-label" for="lastname">Фамилия</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="lastname" name="lastname" value="<?php echo Arr::getValue($params, 'lastname', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="control-group" id="cg-firstname">
                <label class="control-label" for="firstname">Имя</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="firstname" name="firstname" value="<?php echo Arr::getValue($params, 'firstname', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="control-group" id="cg-middlename">
                <label class="control-label" for="middlename">Отчество</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="middlename" name="middlename" value="<?php echo Arr::getValue($params, 'middlename', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>


            <div class="control-group" id="cg-gender">
                <label for="gender" class="control-label">Пол</label>
                <div class="controls">
                    <select class="input-xlarge" name="gender" id="gender">
                        <option value="f">Женский</option>
                        <option value="m">Мужской</option>
                        <option value="0" selected>Укажите пол</option>
                    </select>
                </div>
                <span class="help-inline"></span>
            </div>


            <div class="control-group" id="cg-job">
                <label class="control-label" for="job">Должность</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="job" name="job" value="<?php echo Arr::getValue($params, 'job', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="control-group" id="cg-phone">
                <label class="control-label" for="phone">Тел.</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="phone" name="phone" value="<?php echo Arr::getValue($params, 'phone', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="control-group" id="cg-mail">
                <label class="control-label" for="mail">Email</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="mail" name="mail" value="<?php echo Arr::getValue($params, 'mail', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="control-group" id="cg-im">
                <label class="control-label" for="im">Другое</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="im" name="im" value="<?php echo Arr::getValue($params, 'im', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>





            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="addCnt-submit"><i class="icon-ok icon-white"></i> Сохранить</button>
                <button type="reset" class="btn btn-danger" id="addCnt-cancel"><i class="icon-remove icon-white"></i> Отменить</button>
            </div>
        </fieldset>
    </form>
</div>


<script>

    function openCntFormDialog(data, onSubmit) {
        data = data || {};
        onSubmit = onSubmit || function(){};

        var values = {
            action      : '<?php echo ACTIONS::CONTACT_NEW; ?>',
            id          : 0,
            firstname   : '',
            lastname    : '',
            middlename  : '',
            gender      : 0,
            mail        : '',
            im          : '',
            job         : '',
            phone       : ''
        }

        $.extend(values, data);

        var elms = Elm.addCntForm[0].elements;

        for (var i in elms) {
            if (!elms.hasOwnProperty(i)) continue;
            var tag = elms[i];
            var tn = tag.tagName || false;
            if (!tn) continue;
            tn = tn.toLowerCase();
            if (tag.id && tn == 'input' || tn == 'textarea' || tn == 'select') {
                if (values.hasOwnProperty(tag.id)) $(tag).val(values[tag.id]);
                else $(tag).val('');
            }
        }

        elms.cnt_id.value = values.id;
        elms.action.value = values.action;

        Elm.addCntFormCont.dialog('open');
        if (typeof(onSubmit) == 'function') Elm.addCntFormCont.onSubmit = onSubmit;
        else Elm.addCntFormCont.onSubmit = function(){};


    }

    function closeCntFormDialog() {
        Elm.addCntFormCont.dialog('close');
    }


    function cntWrongFields(wf) {
        wf = wf || {};
        var wf_count = 0;

        var cgdivs = Elm.addCntForm.find('div.error').removeClass('error');
        cgdivs.find('span.help-inline').empty();

        for(var id in wf) {
            if (!wf.hasOwnProperty(id)) continue;
            var msg = wf[id];

            var cg = $('#cg-'+id).addClass('error');
            cg.find('span.help-inline').html(msg);
            wf_count++;
        }
        return wf_count;
    }



    function cntFormDisable() {
        $(Elm.addCntForm[0].elements).attr('disabled','disabled');
    }

    function cntFormEnable() {
        $(Elm.addCntForm[0].elements).removeAttr('disabled');
    }



    function addNewContact(successCallback) {
        successCallback = successCallback || false;
        if (!(typeof(successCallback)=='function')) successCallback = function() {};

        var wf = cntWrongFields();


        openCntFormDialog(
            {},
            function() {
                var wf = cntWrongFields();
                var send = Elm.addCntForm.serialize();
                cntFormDisable();

                jsonRequest(
                    'contacts.php',
                    send,

                    function(data) {
                        if(!checkSession(data)) {
                            Elm.loginFormModal.dialog('open');
                            cntFormEnable();
                            return;
                        }
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            cntFormEnable();
                            return;
                        }
                        if (data.hasOwnProperty('response_data') && data.response_data) {
                            var resp = data.response_data;
                            if (resp.hasOwnProperty('wrongFields')) {
                                var wf = cntWrongFields(resp.wrongFields);
                            }
                        }


                        if (data.hasOwnProperty('relocate') && data.relocate) window.location.assign(data.relocate);
                        else if (data.hasOwnProperty('request_data')
                                && data.request_data
                                && data.request_data.hasOwnProperty('action')
                                && (data.request_data.action = '<?php echo ACTIONS::CONTACT_NEW; ?>')
                                && !wf
                        ){
                            //uiAlert('Изменения сохранены','Информация');
                            closeCntFormDialog();
                            successCallback();
                        }

                        cntFormEnable();
                    },

                    function() {
                        uiAlert('Ошибка соединения','Error');
                        cntFormEnable();
                    }
                );
            }
        );
    }


    function editContact(cdata, successCallback) {
        successCallback = successCallback || false;
        if (!(typeof(successCallback)=='function')) successCallback = function() {};

        var wf = cntWrongFields();
        cdata.action = '<?php echo ACTIONS::CONTACT_UPDATE; ?>';


        openCntFormDialog(
            cdata,
            function() {
                var wf = cntWrongFields();
                var send = Elm.addCntForm.serialize();
                cntFormDisable();

                jsonRequest(
                    'contacts.php',
                    send,

                    function(data) {
                        if(!checkSession(data)) {
                            Elm.loginFormModal.dialog('open');
                            cntFormEnable();
                            return;
                        }
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            cntFormEnable();
                            return;
                        }
                        if (data.hasOwnProperty('response_data') && data.response_data) {
                            var resp = data.response_data;
                            if (resp.hasOwnProperty('wrongFields')) {
                                var wf = cntWrongFields(resp.wrongFields);
                            }
                        }


                        if (data.hasOwnProperty('relocate') && data.relocate) window.location.assign(data.relocate);
                        else if (data.hasOwnProperty('request_data')
                                && data.request_data
                                && data.request_data.hasOwnProperty('action')
                                && (data.request_data.action = '<?php echo ACTIONS::CONTACT_UPDATE; ?>')
                                && !wf
                        ){
                            //uiAlert('Изменения сохранены','Информация');
                            closeCntFormDialog();
                            successCallback(data);
                        }

                        cntFormEnable();
                    },

                    function() {
                        uiAlert('Ошибка соединения','Error');
                        cntFormEnable();
                    }
                );
            }
        );
    }



    $(function() {
        Elm.addCntFormCont = $('#addCntForm-cont');
        Elm.addCntForm = $('#addCntForm');

        Elm.addCntCancelBtn = $('#addCnt-cancel');
        Elm.addCntSubmitBtn = $('#addCnt-submit');


        Elm.addCntFormCont.dialog({
            width       : 350,
            modal       : true,
            resizable   : false,
            draggable   : false,
            title       : "Редактировать контакт",
            autoOpen    : false,
            zIndex      : 6001,
            buttons     : {}
        }).removeClass('hidden');
        Elm.addCntFormCont.dialog('widget').find('a.ui-dialog-titlebar-close').hide(); // прячем крестик

        Elm.addCntFormCont.onSubmit = function(){};

        Elm.addCntForm.submit(function(e) {
            e.preventDefault();
            Elm.addCntSubmitBtn.click();
            return false;
        });


        Elm.addCntSubmitBtn.click(function(e) {
            e.preventDefault();
            if ((Elm.addCntFormCont.hasOwnProperty('onSubmit')) && typeof(Elm.addCntFormCont.onSubmit) == 'function') Elm.addCntFormCont.onSubmit();
            return false;
        });

        Elm.addCntCancelBtn.click(function() {
            closeCntFormDialog();
        });
        //openCntFormDialog({action:123, id:456, lastname:'pupkine'});

    });
</script>